package com.rxb.blog.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;

/**
 * Author：rxb
 * Date：2020-02-20 22:47
 * Description：发邮件
 */
@Component
public class EmailUtil {
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    public void sendEmail(String title, String text, String toEmail) throws AddressException, MessagingException, IOException {
        Properties pro = new Properties();
        pro.put("mail.smtp.host", "smtp.qq.com");
        pro.put("mail.smtp.auth", "true");
        //pro.setProperty("mail.smtp.starttls.enable", "true");
        Authenticator auth = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }

        };
        Session session = Session.getInstance(pro, auth);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, toEmail);
        msg.setSubject(title);
        msg.setContent(text, "text/html;charset=utf-8");

        Transport.send(msg);
    }

}
